﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.User
{
    /// <summary>CCPSIP_037：取得 User 個人圖片(大頭照) API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// UserID = 欲取得圖片的 UserID（包括機器人）。

    public class icon_get : IHttpHandler
    {
        private string kIconDirLatest = ChrisKit.RootDir + "CCPSIP\\UserIcon\\Latest"; //ios.ccp
        private string kIconPathDefaultUser = ChrisKit.RootDir + "CCPSIP\\UserIcon\\Default\\User.jpg";  //ios.ccp
        private string kIconPathDefaultRobot = ChrisKit.RootDir + "CCPSIP\\UserIcon\\Default\\Robot.jpg";//ios.ccp


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string UserID = req.Form["UserID"];//欲取得圖片的UserID

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查檔案路徑問題(防路徑攻擊)
                //
                if (UserID.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    throw new Exception("Error_02: UserID Error");//User帳號錯誤
                }


                //【03】組合檔案路徑
                //
                string iconFileName = string.Format("{0}.jpg", UserID);
                string iconPath = string.Format(@"{0}\{1}", kIconDirLatest, iconFileName);

                if (!File.Exists(iconPath))
                {
                    if (RobotKit.isRobot(UserID))
                        iconPath = kIconPathDefaultRobot;
                    else
                        iconPath = kIconPathDefaultUser;
                }


                //【99】回傳HTTP Header與圖片檔案
                // http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
                //
                FileInfo fInfo = new FileInfo(iconPath);
                resp.ContentType = "image/jpeg";
                resp.AppendHeader("Content-Length", fInfo.Length.ToString());
                resp.AppendHeader("Last-Modified", fInfo.LastWriteTime.ToUniversalTime().ToString("r"));
                resp.AppendHeader("Content-Disposition", ChrisKit.getContentDisposition(iconFileName));
                resp.AppendHeader("Cache-Control", "no-cache");

                resp.WriteFile(iconPath, true);//Small File
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                string resultStr = ChrisKit.Ex2Xml(ex, false);
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
            }
            finally
            {
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
